﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;

namespace Kea
{
    public class DataPlanLookupable<T, TResult> : DataPlanFilterable<T> where T : TableReaderWriter<T>, new()
    {
        internal DataPlanLookupable() { }

        internal Func<T, TResult> LookupResultFunction { get; set; }
        internal TResult DefaultValue { get; set; }

        private sealed class LookupJoinable : Joinable<TResult>
        {
            private TRWManager<T> Man = null;

            public override void Dispose()
            {
                if (Man == null) return;
                ((IDisposable)Man).Dispose();
                Man = null;
            }


            private readonly DataPlanLookupable<T, TResult> _dataPlanLookup;
            public LookupJoinable(DataPlanLookupable<T, TResult> dataPlanLookup) { _dataPlanLookup = dataPlanLookup; }
            private bool _rowFound;
            public override bool Read()
            {
                if (FirstTimeForThisKey)
                {
                    FirstTimeForThisKey = false;
                    if (Man == null) Man = new TRWManager<T>(_dataPlanLookup);
                    _rowFound = Man.ReadToStartOfRange(_keys);
                    return true;
                }
                return false;
            }
            public override TResult GetData()
            {
                if (_rowFound)
                {
                    var v = _dataPlanLookup.LookupResultFunction(Man.Item);
                    if (v != null) return v;
                }

                return _dataPlanLookup.DefaultValue;
            }
        }

        internal Func<Joinable<TResult>> GetJoinableLookup()
        {
            return () => new LookupJoinable(this);
        }
    }
}
